// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.documentCirculation.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.documentCirculation.entity.DataTaskMapping;
import com.fowo.api.documentCirculation.mapper.DataTaskMappingMapper;
import com.fowo.api.documentCirculation.model.DataTaskMappingExcelPo;
import com.fowo.api.documentCirculation.model.DataTaskMappingImportPo;
import com.fowo.api.documentCirculation.model.DataTaskMappingItemVo;
import com.fowo.api.documentCirculation.model.DataTaskMappingSearchParamPo;
import com.fowo.api.documentCirculation.model.DataTaskMappingVo;
import com.fowo.api.documentCirculation.service.DataTaskMappingService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据事务映射表 服务实现类
 */
@Service
@Slf4j
@DS("ds30")
public class DataTaskMappingServiceImpl
  extends ServiceImpl<DataTaskMappingMapper, DataTaskMapping>
  implements DataTaskMappingService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("branchIdFromTable", "dtb.`from_table`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected FileService fileService;

  @Resource
  protected Validator validator;

  /**
   * 创建数据事务映射表
   * @param model 数据事务映射表
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(DataTaskMappingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    DataTaskMapping entity = new DataTaskMapping();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("数据事务映射表保存失败");
  }

  /**
   * 批量更新 数据事务分支 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByBranchId(
    Long branchId,
    List<DataTaskMappingItemVo> list
  ) throws Exception {
    // 删除处理
    List<Long> noDeleteIds = new ArrayList<>();
    for (DataTaskMappingItemVo itemVo : list) {
      if (itemVo.getId() != null && !Boolean.TRUE.equals(itemVo.getDelFlag())) {
        noDeleteIds.add(itemVo.getId());
      }
    }

    if (!noDeleteIds.isEmpty()) {
      baseMapper.delete(Wrappers.<DataTaskMapping>query()
              .eq("branch_id", branchId)
              .notIn("id", noDeleteIds)
      );
    } else {
      baseMapper.delete(Wrappers.<DataTaskMapping>query().eq("branch_id", branchId));
    }
    // 新增或编辑
    for (DataTaskMappingItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      DataTaskMapping item = new DataTaskMapping();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getBranchId() == null) {
        item.setId(null);
        item.setBranchId(branchId);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 更新数据事务映射表
   * @param model 数据事务映射表
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(DataTaskMappingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    DataTaskMapping entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("数据事务映射表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    return this.updateById(entity);
  }

  /**
   * 更新数据事务映射表（带空值）
   * @param model 数据事务映射表
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(DataTaskMappingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    DataTaskMapping entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("数据事务映射表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(DataTaskMapping::getBranchId, model.getBranchId())
      .set(DataTaskMapping::getLastUpdateTime, model.getLastUpdateTime())
      .set(DataTaskMapping::getLastUpdateUser, model.getLastUpdateUser())
      .set(DataTaskMapping::getFieldDescription, model.getFieldDescription())
      .set(DataTaskMapping::getType, model.getType())
      .set(DataTaskMapping::getTypeValue, model.getTypeValue())
      .set(DataTaskMapping::getFromField, model.getFromField())
      .set(DataTaskMapping::getToField, model.getToField())
      .set(DataTaskMapping::getShowLabel, model.getShowLabel())
      .set(DataTaskMapping::getSortPosition, model.getSortPosition())
      .eq(DataTaskMapping::getId, model.getId())
      .update();
    return isOk;
  }

  /**
   * 删除数据事务映射表
   * @param id 数据事务映射表的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除数据事务映射表
   * @param ids 数据事务映射表的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @return 导入行对象
   */
  protected ImportRow<DataTaskMappingImportPo> excelToImportRow(
    DataTaskMappingImportPo row,
    Integer rowNumber,
    DataTaskMappingVo vo,
    Map<String, Object> variables
  ) {
    ImportRow<DataTaskMappingImportPo> ir = new ImportRow<DataTaskMappingImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<DataTaskMappingImportPo>> validate = validator.validate(
      row
    );
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new DataTaskMappingVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, DataTaskMappingImportPo.class);

    // 一般数据处理
    vo.setSortPosition(SheetUtils.tryToInteger(row.getSortPosition()));

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   */
  @Override
  public List<ImportRow<DataTaskMappingImportPo>> importPreview(
    SysFile sysFile
  ) throws Exception {
    Map<String, Object> variables = new HashMap<>();
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<DataTaskMappingImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(
          in,
          DataTaskMappingImportPo.class,
          new ReadListener<DataTaskMappingImportPo>() {
            @Override
            public void invoke(
              DataTaskMappingImportPo row,
              AnalysisContext cxt
            ) {
              ImportRow<DataTaskMappingImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                null,
                variables
              );
              if (ir.isEmptyRow()) {
                return;
              }
              rows.add(ir);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(List<ImportRow<DataTaskMappingImportPo>> rows)
    throws Exception {
    Map<String, Object> variables = new HashMap<>();
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<DataTaskMappingImportPo> row = rows.get(i);
      DataTaskMappingVo vo = new DataTaskMappingVo();
      row = excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      create(vo);
    }
  }

  /**
   * 导出
   * @param search 查询条件
   */
  @Override
  public void export(
    DataTaskMappingSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<DataTaskMappingExcelPo> items = new ArrayList<DataTaskMappingExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<DataTaskMappingItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<DataTaskMappingItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (DataTaskMappingItemVo item : list) {
        DataTaskMappingExcelPo excel = new DataTaskMappingExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    ResponseUtils.setAttachmentFileName(response, "数据事务映射表.xlsx");
    EasyExcel
      .write(response.getOutputStream())
      .sheet()
      .head(DataTaskMappingExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过字段描述查询数据事务映射表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByFieldDescription(String fieldDescription) {
    return this.baseMapper.getIdByFieldDescription(fieldDescription);
  }

  /**
   * 通过字段描述查询数据事务映射表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByFieldDescription(List<String> list) {
    return this.baseMapper.getIdsByFieldDescription(list);
  }

  /**
   * 通过数据事务映射表主键查询字段描述
   */
  @Override
  public String getFieldDescriptionById(Long id) {
    return this.baseMapper.getFieldDescriptionById(id);
  }

  /**
   * 通过数据事务映射表主键查询字段描述列表
   */
  @Override
  public List<String> getFieldDescriptionByIds(List<Long> ids) {
    return this.baseMapper.getFieldDescriptionByIds(ids);
  }

  /**
   * 获取详情
   * @param id 数据事务映射表的主键
   */
  @Override
  public DataTaskMappingVo getVoById(Long id) throws Exception {
    DataTaskMappingVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询数据事务映射表
   * @param search 查询条件
   * @return 数据事务映射表分页查询结果
   */
  @Override
  public Page<DataTaskMappingItemVo> pageSearch(
    DataTaskMappingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    Page<DataTaskMappingItemVo> page =
      this.baseMapper.pageSearch(search.toPage(), search);
    return page;
  }

  /**
   * 列表查询数据事务映射表
   * @param search 查询条件
   * @return 数据事务映射表列表查询结果
   */
  @Override
  public List<DataTaskMappingItemVo> search(
    DataTaskMappingSearchParamPo search
  ) {
    search.initSort("t.sort_position asc, t.id asc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询数据事务映射表最后更新时间
   * @param search 查询条件
   * @return 数据事务映射表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(DataTaskMappingSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
